angular.module('helloApp')
.service('Auth', function($http, $cookieStore, $state, LoginService){

    var accessLevels = routingConfig.accessLevels
        , userRoles = routingConfig.userRoles
        , currentUser = $cookieStore.get('user') || { username: '', role: userRoles.public };

    //$cookieStore.remove('user');

    function changeUser(user) {
        angular.extend(currentUser, user);
        $cookieStore.put("user", currentUser);
    }

    return {
        authorize: function(accessLevel, role) {
            if(role === undefined) {
                role = currentUser.role;
            }

            return accessLevel.bitMask & role.bitMask;
        },
        isLoggedIn: function(user) {
            if(user === undefined) {
                user = currentUser;
            }
            return user.role.title === userRoles.user.title || user.role.title === userRoles.admin.title;
        },
        /*register: function(user, success, error) {
            $http.post('/register', user).success(function(res) {
                changeUser(res);
                success();
            }).error(error);
        },*/
        login: function(user) {
            LoginService.login(user, function(data) {
                user.role = userRoles.admin;
                //user.role = data.roles[0];
                changeUser(user);
                $state.go('root.admin.home');
            });
        },
        logout: function() {
            LoginService.logout(function() {
                changeUser({
                    username: '',
                    role: userRoles.public
                });
                $state.go('root.anon.login');
            });
        },
        accessLevels: accessLevels,
        userRoles: userRoles,
        user: currentUser
    };
});